package com.travel.server.manager.impl.command.project.data;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.DateUtil;
import com.travel.server.manager.impl.command.BaseImportCommand;
import com.travel.server.manager.model.ProjectSpecial;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/4 10:37
 * @Desc:
 */
@Component
@Slf4j
public class ImportProjectCostCommand extends BaseImportCommand {

    public void handle(InputStream fileInputStream, UserInfo userInfo){
        Date now = new Date();
        try {
            List<ProjectSpecial> specialList = new ArrayList<>();
            Map<String, ProjectSpecial> projectMap = new HashMap<>();
            Set<String> notExistProject = new HashSet<>();
            XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = wb.getSheetAt(0);
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                XSSFRow row = sheet.getRow(rowNum);
                XSSFCell cell0 = row.getCell(0);
                if (cell0 == null || cell0.getCellType() == XSSFCell.CELL_TYPE_BLANK) {
                    break;
                }
                String projectName = getValue(cell0);
                String travelDateStr = getValue(row.getCell(1));
                String project = getValue(row.getCell(2));
                String apply = getValue(row.getCell(3));
                String partner = getValue(row.getCell(4));
                String discount = getValue(row.getCell(5));
                String compensate = getValue(row.getCell(6));
                String taxation = getValue(row.getCell(7));
                String insurance = getValue(row.getCell(8));
                String travel = getValue(row.getCell(9));
                String material = getValue(row.getCell(10));
                String remark = getValue(row.getCell(11));
                Date travelDate;
                try{
                    travelDate = DateUtil.YYYY_MM_DD.parse(travelDateStr);
                }catch (Exception e){
                    throw new WorkException(WorkCode.EXCEL_DATE_NOT_CORRECT);
                }
                String specialMsg = projectName + CommonConstant.DASH_STR + travelDateStr;
                ProjectSpecial special = projectMap.get(specialMsg);
                if(special == null) {
                    special = querySpecial(projectName, travelDate);
                }
                if(special == null){
                    log.info("未查询到项目名称 {} 和出行日期 {} 对应的项目规格", projectName, travelDateStr);
                    notExistProject.add(notExistProject +specialMsg + CommonConstant.SEMICOLON_STR);
                    continue;
                }
                projectMap.put(specialMsg, special);
                special.setProject(getNewAmount(special.getProject(), project));
                special.setApply(getNewAmount(special.getApply(), apply));
                special.setPartner(getNewAmount(special.getPartner(), partner));
                special.setDiscount(getNewAmount(special.getDiscount(), discount));
                special.setCompensate(getNewAmount(special.getCompensate(), compensate));
                special.setTaxation(getNewAmount(special.getTaxation(), taxation));
                special.setInsurance(getNewAmount(special.getInsurance(), insurance));
                special.setTravel(getNewAmount(special.getTravel(), travel));
                special.setMaterial(getNewAmount(special.getMaterial(), material));
                special.setRemark(StringUtils.isBlank(remark) ? remark : special.getRemark() + CommonConstant.SEMICOLON_STR + remark);
                special.setUpdateTime(now);
                special.setUpdateBy(userInfo.getName());
                specialList.add(special);
            }

            if(!CollectionUtil.isEmpty(notExistProject)){
                String message = CommonConstant.EMPTY_STR;
                for(String msg : notExistProject){
                    message = message + msg + CommonConstant.SEMICOLON_STR;
                }
                message = message.substring(0, message.length() - 1);
                WorkCode workCode = WorkCode.PROJECT_SPECIAL_NOT_EXIST;
                workCode.setMessage(PROJECT_NOT_EXIST_PRE + message);
                throw new WorkException(workCode);
            }

            for(ProjectSpecial special : specialList){
                specialDal.insertOrUpdate(special);
            }
        }catch (WorkException e){
            throw e;
        }catch (Exception e){
            log.error("导入项目成本Excel异常：", e);
            throw new WorkException(WorkCode.SYSTEM);
        }
    }

    private Integer getNewAmount(Integer oldAmount, String str){
        Integer amount = getAmount(str);
        if(oldAmount == null){
            return amount;
        }
        return amount + oldAmount;
    }

    private Integer getAmount(String str){
        if(StringUtils.isBlank(str)){
            return 0;
        }
        BigDecimal num = new BigDecimal(str);
        return num.multiply(new BigDecimal(100)).intValue();
    }
}
